import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getTimestamp } from '@/utils/auth'

const timeout = 3600

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url 基础地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // 超时时间
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // 在这个位置需要统一的去注入token
    if (store.getters.token) {
      // 检查token是否超时
      if (isCheckTimeOut()) {
        // 登出操作
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token超时了'))
      }
      // 如果token存在 注入token
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config // 必须返回配置
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(message || 'Error'))
    }
  },
  (error) => {
    // 服务器返回超时状态码
    if (error.response && error.response.data && error.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error) // 返回执行错误,让当前的执行链退出,进入catch
  }
)

// 检查token是否超时
function isCheckTimeOut() {
  var currentTime = Date.now()
  var timeStamp = getTimestamp()
  return (currentTime - timeStamp) / 1000 > timeout
}
export default service
